import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { login, getAuthElement } from '@/api/login.js';
import { useDispatch } from 'react-redux'
import { setToken, setUserInfo,setAuthElement } from '@/store/user';
import { resetTabs } from '@/store/tabs';
import { Form, Input, Button, Card } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import styles from './LoginPage.module.css';

const LoginPage = () => {
  const [isLoading, setIsLoading] = useState(false);
  
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const onFinish = (values) => {
    setIsLoading(true);
    
    login(values)
      .then(res => {
        dispatch(setToken(res.data.token));
        dispatch(setUserInfo(res.data.userInfo));
        dispatch(resetTabs());
        getAuthElement().then(res => {
          dispatch(setAuthElement(res.data));
          navigate('/');
        });
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  return (
    <div className={styles.loginContainer}>
      <Card className={styles.loginCard} title={
        <div className={styles.loginHeader}>
          <h2 className={styles.loginTitle}>系统登录</h2>
          <p className={styles.loginSubtitle}>请输入您的账号和密码</p>
        </div>
      }>
        <Form
          name="login_form"
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input 
              prefix={<UserOutlined />} 
              placeholder="用户名" 
              disabled={isLoading}
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              disabled={isLoading}
            />
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={isLoading}
              block
            >
              登录
            </Button>
          </Form.Item>
          
          <div className={styles.demoInfo}>
            <span>演示账号: admin</span>
            <span>密码: 123456</span>
          </div>
        </Form>
      </Card>
    </div>
  );
};

export default LoginPage;